package org.zcl.rocketmq.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.zcl.rocketmq.consumer.AbstractFlowConsumer;
import org.zcl.rocketmq.entity.MessageObj;
import org.zcl.rocketmq.event.MessageEvent;
import org.zcl.rocketmq.utils.ApplicationContextHelper;

import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class MessageListener implements ApplicationListener<MessageEvent> {

    @Autowired
    private ApplicationContextHelper applicationContextHelper;

    @Async
    @Override
    public void onApplicationEvent(MessageEvent event) {

        try {
            log.info("spring listener receiver  " + event.getMessage());
            MessageObj messageObj = JSON.parseObject(event.getMessage(),MessageObj.class);
            log.info("流程ID【{}】，流程实例ID【{}】",messageObj.getFlowId(),messageObj.getInstanceId());
            Map<String, AbstractFlowConsumer> beanMap = applicationContextHelper.getBeansOfType(AbstractFlowConsumer.class);
            AbstractFlowConsumer abstractFlowConsumer = beanMap.get(messageObj.getQueue());
            if(Objects.nonNull(abstractFlowConsumer)){
                abstractFlowConsumer.doWork(event.getMessage());
            }else{
                log.error("未找到名为{}的springBean",messageObj.getQueue());
            }
        } catch (Exception ex) {
            log.error("springEvent 订阅异常",ex);
        }
    }
}
